package com.xbongbong.pro.statistic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.service.toolbox.statistic.help.PkHelp;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.pro.statistic.manager.feign.PaasFormFeignClient;
import com.xbongbong.pro.statistic.model.ChartCustomModel;
import com.xbongbong.pro.statistic.result.pojo.ChartIdPojo;
import com.xbongbong.pro.statistic.result.pojo.dto.ChartResultDTO;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartResultVO;
import com.xbongbong.pro.statistic.service.ChartCustomService;
import com.xbongbong.pro.statistic.service.ChartResultService;
import com.xbongbong.pro.statistic.through.pojo.dto.ResultThroughDTO;
import com.xbongbong.pro.statistic.through.pojo.vo.IndexThroughDTO;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 自定义指标、图表
 * @author xinpeng.jiang
 * @date 2021/5/14 10:13
 * @version 1.0
 * @since V1.0
 */
@Service("ChartCustomService")
public class ChartCustomServiceImpl implements ChartCustomService {

    private static final Logger LOG = LoggerFactory.getLogger(ChartCustomServiceImpl.class);
    @Resource
    private ChartCustomModel chartCustomModel;
    @Resource
    private PaasFormFeignClient paasFormFeignClient;
    @Resource
    private UserModel userModel;
    @Resource
    private ChartResultService chartResultService;
    @Resource
    private PkHelp pkHelp;

    @Override
    public IndexThroughDTO customPkResultThrough(ResultThroughDTO resultThroughDTO) throws XbbException {
        // feign调用自定义指标的穿透解析
        String result = paasFormFeignClient.customChartResultThrough(resultThroughDTO, LocaleContextHolder.getLocale().toString());
        // 反序列化
        XbbResponse<IndexThroughDTO> xbbResponse = JSON.parseObject(result, new TypeReference <XbbResponse<IndexThroughDTO>>() {
        }, Feature.OrderedField);
        if(!xbbResponse.isSuccess()){
            //rpc服务报错，远程抛出
            throw new XbbException(xbbResponse.getCode(), I18nMessageUtil.getMessage(xbbResponse.getMsg()));
        }

        IndexThroughDTO indexThroughDTO = xbbResponse.getResult();
        // 处理表头
        Long chartId = resultThroughDTO.getId();
        ChartEntity chartEntity = chartCustomModel.getByKey(chartId, resultThroughDTO.getCorpid());
        JSONArray penetrateAttr = chartEntity.getPenetrateAttr();
        List<FieldAttrEntity> headList = indexThroughDTO.getHeadList();
        pkHelp.handleCustomPkThroughHead(headList);
        // 处理自定义表头
        if (penetrateAttr != null && penetrateAttr.size() > 0) {
            List<String> attrList = new ArrayList<>();
            for (Object o : penetrateAttr) {
                JSONObject obj = o instanceof JSONObject ? (JSONObject) o : null;
                if (obj == null) {
                    continue;
                }
                String attr = (String)obj.get(StringConstant.ATTR);
                attrList.add(attr);
            }
            headList.removeIf(fieldAttrEntity -> !attrList.contains(fieldAttrEntity.getAttr()));
        }
        // 处理标题
        String startTime = DateUtil.getDateString(resultThroughDTO.getStartTime());
        String endTime = DateUtil.getDateString(resultThroughDTO.getEndTime());
        List<UserEntity> entitysByUserIds = userModel.findEntitysByUserIds(Collections.singletonList(resultThroughDTO.getCheckedUserId()), resultThroughDTO.getCorpid());
        if (CollectionsUtil.isNotEmpty(entitysByUserIds)) {
            indexThroughDTO.setHead(entitysByUserIds.get(0).getName() + startTime + "到" + endTime + chartEntity.getName());
        }

        return indexThroughDTO;
    }

    @Override
    public ChartResultVO customPkMobileResultThrough(ResultThroughDTO resultThroughDTO) throws XbbException {
        ChartResultVO chartResultVO = new ChartResultVO();
        try {
            String corpid = resultThroughDTO.getCorpid();
            ChartEntity chartEntity = chartCustomModel.getByKey(resultThroughDTO.getId(), corpid);
            List<JSONObject> search = new ArrayList<>();
            // 处理筛选人
            JSONObject belongAttr = chartEntity.getBelongAttr();
            belongAttr.put(StringConstant.VALUE, resultThroughDTO.getCheckedUserId());
            belongAttr.put(StringConstant.SYMBOL, ConditionEnum.EQUAL.getSymbol());
            search.add(belongAttr);
            // 处理筛选时间
            JSONObject timeAttr = chartEntity.getTimeAttr();
            timeAttr.put(StringConstant.VALUE, Arrays.asList(resultThroughDTO.getStartTime(), resultThroughDTO.getEndTime()));
            timeAttr.put(StringConstant.SYMBOL, ConditionEnum.RANGE.getSymbol());
            search.add(timeAttr);
            // 走数据查询表逻辑
            ChartResultDTO chartResultDTO = new ChartResultDTO();
            BeanUtil.copyProperties(resultThroughDTO, chartResultDTO);
            chartResultDTO.setChartIdIn(Collections.singletonList(new ChartIdPojo(resultThroughDTO.getId(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())));
            chartResultDTO.setSearch(search);
            chartResultVO = chartResultService.chartResult(chartResultDTO);
        } catch (XbbException e) {
            LOG.error("自定义pk移动端穿透报错:", e);
            e.printStackTrace();
        }
        return chartResultVO;
    }

}
